package com.yoomiito.app.ui.push

import android.content.Context
import android.os.Build
import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.NetProvider
import cn.droidlover.xdroidmvp.net.RequestHandler
import cn.droidlover.xdroidmvp.net.XApi
import com.alibaba.fastjson.JSONObject
import com.taobao.accs.ACCSClient
import com.taobao.accs.AccsClientConfig
import com.taobao.agoo.TaobaoRegister
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.commonsdk.UMConfigure
import com.umeng.commonsdk.utils.UMUtils
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import com.umeng.message.UmengNotificationClickHandler
import com.umeng.message.entity.UMessage
import com.umeng.message.tag.TagManager
import com.umeng.socialize.PlatformConfig
import com.umeng.socialize.UMShareAPI
import com.yoomiito.app.BuildConfig
import com.yoomiito.app.Constant
import com.yoomiito.app.base.App
import com.yoomiito.app.base.AppClient
import com.yoomiito.app.base.AppConfig
import com.yoomiito.app.base.CurrentUser
import com.yoomiito.app.broadcastreceiver.NetStateReceiver.Companion.registerReceiver
import com.yoomiito.app.model.bean.BannerAndIconInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.utils.ActTypeUtils
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.TouchUtils
import io.reactivex.schedulers.Schedulers
import okhttp3.CookieJar
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import org.android.agoo.huawei.HuaWeiRegister
import org.android.agoo.mezu.MeizuRegister
import org.android.agoo.oppo.OppoRegister
import org.android.agoo.vivo.VivoRegister
import org.android.agoo.xiaomi.MiPushRegistar


object UMManager{
//    private var job: Job = Job()
//    override val coroutineContext: CoroutineContext
//        get() = job + Dispatchers.IO
//object UMManager{

    /**
     * 预初始化，已添加子进程中初始化sdk。
     * 使用场景：用户未同意隐私政策协议授权时，延迟初始化
     *
     * @param context 应用上下文
     */
    fun preInit(context: Context?) {
//        try {
//            //解决推送消息显示乱码的问题
//            val builder: AccsClientConfig.Builder = AccsClientConfig.Builder()
//            builder.setAppKey("umeng:" + Constant.UM_APP_KEY)
//            builder.setAppSecret(Constant.UM_MSG_Secret)
//            builder.setTag(AccsClientConfig.DEFAULT_CONFIGTAG)
//            ACCSClient.init(context, builder.build())
//            TaobaoRegister.setAccsConfigTag(context, AccsClientConfig.DEFAULT_CONFIGTAG)
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
        UMConfigure.preInit(context, Constant.UM_APP_KEY, "Umeng")
//        if (!isMainProcess(context)) {
//            initUm()
//        }
    }

    fun initUm() {
        //微信
        PlatformConfig.setWeixin(Constant.WECHAT_APP_ID, Constant.WECHAT_APP_SECRET)
        App.msgApi = WXAPIFactory.createWXAPI(App.getApplication(), Constant.WECHAT_APP_ID, false)
        PlatformConfig.setWXFileProvider("com.qiannianai.app.fileprovider")
        registerReceiver()
        registerMvp()
        App.mAppConfig = AppConfig(AppClient(YmApi.getYmService()), CurrentUser())
        UMConfigure.init(App.getApplication(), Constant.UM_APP_KEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, Constant.UM_MSG_Secret)
        if (BuildConfig.DEBUG) UMConfigure.setLogEnabled(true)
        UMShareAPI.get(App.getApplication())
        TouchUtils.startPageCollection()
        CrashReport.initCrashReport(App.getApplication(), "36aa486e95", false)
        //注册推送服务，每次调用register方法都会回调该接口
        PushAgent.getInstance(App.getApplication()).register(object : IUmengRegisterCallback {
            override fun onSuccess(deviceToken: String) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                L.i("注册成功：deviceToken：-------->  $deviceToken")
            }

            override fun onFailure(s: String, s1: String) {
                L.e("注册失败：-------->  s:$s,s1:$s1")
            }
        })
        when (Build.BRAND) {
            "Xiaomi" -> MiPushRegistar.register(App.getApplication(), "2882303761520303660", "5552030353660")
            "HUAWEI" -> HuaWeiRegister.register(App.getApplication())
            "Meizu" -> MeizuRegister.register(App.getApplication(), "124190", "5abadabf907047caa8d1aad63639568a")
            "vivo" -> VivoRegister.register(App.getApplication())
            "oppo" -> OppoRegister.register(App.getApplication(), "a1b90190c106487da82ab1ffd0beea43", "a3d9f377a2ba435e962feff53014a04a")
        }
        PushAgent.getInstance(App.getApplication()).notificationClickHandler = object : UmengNotificationClickHandler() {
            override fun dealWithCustomAction(p0: Context?, p1: UMessage?) {
                super.dealWithCustomAction(p0, p1)
                val bannerInfo = JSONObject.parseObject(p1?.custom,BannerAndIconInfo::class.java)
//                val am =  App.getApplication().getSystemService(ACTIVITY_SERVICE) as ActivityManager
//                val cn = am.getRunningTasks(1)[0].topActivity
                ActTypeUtils.handleActFromType(p0!!,bannerInfo)
            }
        }
    }

    //    @Override
    //    protected void attachBaseContext(Context base) {
    //        super.attachBaseContext(base);
    //        MultiDex.install(this) ;
    //    }
    private fun registerMvp() {
        XApi.registerProvider(object : NetProvider {
            override fun configInterceptors(): Array<Interceptor?> {
                return arrayOfNulls(0)
            }


            override fun configHttps(builder: OkHttpClient.Builder) {
                builder.addInterceptor { chain ->
                    val token = SharedPref.getInstance(App.getApplication())
                        .getString(Constant.TOKEN, "")
                    //                        String token = "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8veW1tdC1hcGkuY29tL3Ntc192ZXJpZnlfY29kZSIsImlhdCI6MTU3ODcxMzU1NiwiZXhwIjo4Nzk3ODcxMzU1NiwibmJmIjoxNTc4NzEzNTU2LCJqdGkiOiJvdldqT0Y2d1NQYXc0MFVxIiwic3ViIjo2NTc5OTEyMDYyMzMwMjA4MjU3LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.KnSPMQxd_outqoDSTgRfB4iHM7FUr5olajDV7B6t8kY";
                    val request = chain.request()
                        .newBuilder()
                        .header("Authorization", token)
                        .header("Site", "app_mugwort_android") //
                        //                                .header("Authorization", "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTkyLjE2OC4xMC4xMzM6ODA4MC9zbXNfdmVyaWZ5X2NvZGUiLCJpYXQiOjE1NzAxNzE4MjQsImV4cCI6MTYzMjM3OTgyNCwibmJmIjoxNTcwMTcxODI0LCJqdGkiOiJZRlhhQ0liVXkyelpuU3hIIiwic3ViIjo0Nzg4ODYwMjYwMTk2MDk2LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.w8aguwN7x0Os8HR-IC7WpJGeVL621Fsg9BsFVk1yzUE")
                        .header("Platform", "")
                        .build()
                    //                                .header("platform", "1")
                    //                                .header("device_model", Build.BRAND + " " + Build.MODEL)
                    //                                .header("device_system", Build.VERSION.RELEASE);//设备型号
                    //
                    //                        builder1.header();
                    //                                .header("device_id ", )//设备id
                    //                                .header("system", )
                    //                        Request request = builder1.build();
                    chain.proceed(request)
                }
            }

            override fun configCookie(): CookieJar? {
                return null
            }

            override fun configHandler(): RequestHandler? {
                return null
            }

            override fun configConnectTimeoutMills(): Long {
                return 0
            }

            override fun configReadTimeoutMills(): Long {
                return 0
            }

            override fun configLogEnable(): Boolean {
                return true
            } //286961

            override fun handleError(error: ApiException): Boolean {
                return false
            }

            override fun dispatchProgressEnable(): Boolean {
                return false
            }
        })
    }

    fun addTags(vararg tag: String) {
        tag.forEach { L.i("设置为标签为$it") }

        PushAgent.getInstance(App.getApplication())
                .tagManager
                .addTags(TagManager.TCallBack { isSuccess, result ->
                    L.i("设置标签结果：$isSuccess   $result")
                },
                *tag)
    }

    fun addAlias(alias: String) {
        PushAgent.getInstance(App.getApplication()).addAlias(
                alias,
                "user_id"
        ) { isSuccess, message ->
            L.i("添加别名结果：$isSuccess    $message")
            pushAlias(alias)
        }
    }

    /**
     * 上传alias
     */
    private fun pushAlias(alias: String) {
        YmApi.getYmService()
                .pushAlias(alias,"1")
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .subscribeOn(Schedulers.io())
                .subscribe(object : ApiSubscriber<BaseModel<*>>(){
                    override fun onSuccess(baseModel: BaseModel<*>) {
                        L.i("上传别名成功：$baseModel")
                    }

                    override fun onFail(error: ApiException) {
                        L.i("上传别名失败：$error")
                    }
                })

    }

    fun delAlias(alias: String) {
        PushAgent.getInstance(App.getApplication()).deleteAlias(
                alias,
                "user_id"
        ) { isSuccess, message ->
            L.i("删除别名结果：$isSuccess    $message")
        }
    }

    /**
     * 是否运行在主进程
     *
     * @param context 应用上下文
     * @return true: 主进程；false: 子进程
     */
    fun isMainProcess(context: Context?): Boolean {
        return UMUtils.isMainProgress(context)
    }
}